﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using todo;

namespace gtasks.Auth
{
    public partial class AuthForm : Form
    {
        private string _code;

        public AuthForm()
        {
            InitializeComponent();

            //
            www.DocumentCompleted += www_DocumentCompleted;
            www.DocumentTitleChanged += www_DocumentTitleChanged;

            var url = "https://accounts.google.com/o/oauth2/auth?" +
                      "response_type=code&" +
                      "client_id=3088305420.apps.googleusercontent.com&" +
                      "redirect_uri=urn:ietf:wg:oauth:2.0:oob&" +
                      "scope=https://www.googleapis.com/auth/tasks";
            www.Navigate(url);

#if zh
            this.Text = "授予todo.EXE管理您的Google任务的权限";
#endif
//            Debug.Print("@@@@@@@@@@@@@@@@@@" + App.MainThreadId + ", " + Thread.CurrentThread.ManagedThreadId);
        }

        void www_DocumentTitleChanged(object sender, EventArgs e)
        {
            lblLoading.Visible = false;
        }

        void www_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
//            Debug.Print("@@@@@@@@@@@@@@@@@@@ www_DocumentCompleted");
            var title = www.Document.Title;

            var eqPrefix = "Success code=";
            if (title.StartsWith(eqPrefix))
            {
                _code = title.Substring(eqPrefix.Length);
                Console.WriteLine(_code);
                www.Visible = false;
                var msg = "Access rights granted.";
                title = "Google tasks";
#if zh
                msg = "授权完成";
                title = "Google 任务";
#endif
                MessageBox.Show(msg, title);

                this.Close();
            }
        }

        public string Code
        {
            get { return _code; }
        }
    }
}
